<!--
* 功能-页面实现
* Date: 2023-7-29
* Author: 靳从毅
 -->
<template>
  <layout-card v-model="search" :filters="deviceOptions" headline="信息列表" headtitle="数据筛选" :hasButton="true"
    @search-change="searchChange" @search-reset="reset">
    <template #action>
      <div class="list-action">
        <el-button type="primary" @click="handleCreate('threshold')">数量阈值</el-button>
        <el-button type="primary" :disabled="isDisabled" @click="handleCreate('export')">导出</el-button>
        <el-button type="primary" @click="handleCreate('download')">模板下载</el-button>
        <el-upload :show-file-list="false" accept=".xlsx,.xls" :on-change="handleImport" :on-exceed="handleExceed" ref="upload" action="#"
          :limit="1" :auto-upload="false" style="margin: 0 0.75rem">
          <el-button type="primary" :loading="btnLoading">导入</el-button>
        </el-upload>
        <el-button type="primary" @click="handleCreate('add')">新增设备</el-button>
      </div>
    </template>

    <table-common stripe :columns="deviceColumns" :loading="loading" :pagination="pager" :table-data="tableData"
      size="large" @current-change="currentChange" @size-change="sizeChange" @sort-change="handleSort">
      <template #action="{ row }">
        <!-- 自定义操作栏示例  -->
        <el-button class="link-btn" @click="handleEdit(row)" link type="primary">编辑</el-button>
        <el-popconfirm title="是否删除?" confirmButtonText="确定" cancelButtonText="取消" @confirm="() => handleDelete(row)">
          <template #reference>
            <el-button class="link-btn" link type="danger">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </table-common>
  </layout-card>
  <!-- 数据阈值 -->
  <edit-dialog :centerDialogVisible="thresholdDialogVisible" :tilte="addTilte" :key="timer" :defaultButton="false"
    :width=500 style="height: 100px" :before-close="Cancel" @Cancel="Cancel">
    <template #content>
      <el-table :data="thresholdData" :pagination="false" height="200px" @row-click="hiddenMe">
        <el-table-column type="index" label="序号" width="60" align="center"/>
        <template v-for="(item, colIndex) in thresholdListColumns" :key="colIndex">
          <el-table-column :label="item.label" :prop="item.prop" :width="item.width" align="center">
            <template #default="scope">
              <el-input-number v-if="isEdit && scope.$index === rowInd && scope.cellIndex === colInd"
                v-model="scope.row[item.prop]" size="small" style="width: 80px" controls-position="right"
                @click.stop="" />
              <el-select v-else-if="isSelect && scope.$index === rowInd && scope.cellIndex === colInd"
                v-model="scope.row[item.prop]" size="small">
                <el-option key="1" label="是" value="是" />
                <el-option key="2" label="否" value="否" />
              </el-select>
              <div v-else @click="cellClick(scope)" style="width: 50px; height: 24px">{{ scope.row[item.prop] }}</div>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button @click="Cancel">取消</el-button>
        <el-button type="primary" @click="Submit">保存</el-button>
      </span>
    </template>
  </edit-dialog>

  <!-- 地图 -->
  <edit-dialog :centerDialogVisible="showMapDialogVisible" :tilte="addTilte" :key="timer" class="showMap"
    :defaultButton="false" :width=1000 :before-close="Cancel" @Cancel="Cancel">
    <template #content>
      <div style="width: 100%; height: 500px; border: 1px solid #000">
        <map-control @mapClick="mapClick" @mapLoad="mapLoadEvent"></map-control>
      </div>
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button @click="Cancel">取消</el-button>
        <el-button type="primary" @click="next">下一步</el-button>
        <el-button type="primary" @click="jump" style="background-color: #FFF; color: #2F7DF1">跳过</el-button>
      </span>
    </template>
  </edit-dialog>

  <!-- 新增/编辑页面 -->
  <edit-dialog :centerDialogVisible="addEquipmentDialogVisible" :tilte="addTilte" :key="timer" :defaultButton="false"
    :width=950 :before-close="Cancel" :rules="rules" @Cancel="Cancel">
    <template #content>
      <FilterBar ref="FilterRef" :close-collapse="true" :filters="dialogEditOptions" :hasButton="false"
        :hasTableButton="hasTableButton" :rules="rules" @search-change="onSearch" @search-reset="onReset"
        @on-toggle="(val: any) => $emit('on-toggle', val)" />
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button @click="Cancel">取消</el-button>
        <el-button @click="back">返回</el-button>
        <el-button type="primary" @click="Submit">保存</el-button>
      </span>
    </template>
  </edit-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, onBeforeMount, computed, nextTick } from 'vue'
import { useStore } from 'vuex'
import FilterBar from '@/components/FilterBar/index.vue'
import LayoutCard from '@/components/LayoutCard/index.vue'
import TableCommon from '@/components/TableCommon/index.vue'
import { deviceColumns, thresholdListColumns } from '@/views/eqpt/water/config/columns'
import { deviceOptions, dialogEditOptions } from '@/views/eqpt/water/config/filters'
import { waterPageList, waterDelete, listExport, PageListType, listDownload, listImport, waterAdd, waterUpdate, geteqptType } from '@/api/eqpt/water'
import editDialog from '@/components/editDialog/index.vue'
import { getResource } from '@/api/resource'
import { dayjs, ElMessage } from 'element-plus'
import type { UploadInstance } from 'element-plus'
// 以下3个为地图控件相关的组件
import mapControl from '@/components/map/index.vue'
import { store } from '@/components/map/mapStore'
import { image } from '@/assets/index'
import {FormRules} from 'element-plus'
const isdeviceOptions = ref(deviceOptions)
isdeviceOptions.value[0].inputProps.options.unshift({ label: '全部', value: '' })

/**
 * 约束
 */
interface SearchType {
  eqptCode?: string
  terminal?: any;
}
interface ProblemType {
  eqptCode?: string
  eqptId?: string
}
/**
  * 功能-清空数据、清空查询条件
  * Date: 2023-7-28
  * Author: 郑钦懋
  */
  const reset = () => {  
  search.value.region.checkAll = false
  // 默认按照设备编号最小的排序
  handleSort({ order: 'ascending', prop: 'eqptCode' })
  getData()
}

/**
  * 功能-查询，并排序
  * Date: 2023-7-28
  * Author: 郑钦懋
  */
 const searchChange = () => {
  handleSort({ order: 'ascending', prop: 'eqptCode' })
  getData()
}

// 判断按钮是否禁用
// 获取数据
// 新增弹窗是否打开
const thresholdDialogVisible = ref(false)
const showMapDialogVisible = ref(false)
const addEquipmentDialogVisible = ref(false)
const isEdit = ref(false)
const isSelect = ref(false)
const rowInd = ref(0)
const colInd = ref(0)
// 用于保存地图坐标及相关信息
const mapPoint = ref({
  x: "",
  y: ""
});
// 点击事件
const mapClick = (evt: any) => {
  // 点位坐标 longitude：evt.mapPoint.x  latitude：evt.mapPoint.y
  // 区域字段在地图数据中暂时没有
  // 移除临时图层
  store.BNMap.removeGraphicsLayer('clickLayer')
  // 向地图添加临时图层
  const clickLayer = store.BNMap.creatGraphicsLayer({ id: 'clickLayer' })
  clickLayer.removeAll()
  // 创建点
  const point = store.BNMap.createPoint({ x: evt.mapPoint.x, y: evt.mapPoint.y, spatialReference: evt.mapPoint.spatialReference })
  // store.BNMap.setCenter(point);
  // 创建图片
  const symbolStyle = store.BNSymbol.PictureMarkerSymbol(image.point, 20, 25)
  // 创建要素
  const picgraphic = store.BNMap.graphic(point, symbolStyle)
  // 添加到地图
  clickLayer.add(picgraphic)
  store.BNMap.addGraphicsLayer(clickLayer)
  // 将相关信息保存到变量
  mapPoint.value.x = evt.mapPoint.x
  mapPoint.value.y = evt.mapPoint.y
  // 地图区域值暂时为空
}
// 7-27新增用于接收弹窗组件值的ref对象
const FilterRef = ref()

// 获取eqptId
const eqptId = ref()

// 时间戳，用于确保弹窗页面能加载不同的界面
const timer = ref()
// 弹窗标题
const addTilte = ref('')
// 导出按钮禁用
const isDisabled = computed(() => {
  return tableData.value.length === 0
})

const mapLoadEvent = () => {
  if (mapPoint.value.x !== "") {
    store.BNMap.removeGraphicsLayer("clickLayer")
    // 向地图添加临时图层
    const clickLayer = store.BNMap.creatGraphicsLayer({ id: "clickLayer" })
    clickLayer.removeAll()
    // 创建点
    const point = store.BNMap.createPoint({
      x: mapPoint.value.x,
      y: mapPoint.value.y,
      spatialReference: store.BNMap.spatialReference,
    })
    store.BNMap.setCenter(point)
    // 创建图片
    const symbolStyle = store.BNSymbol.PictureMarkerSymbol(image.point, 20, 20)
    // 创建要素
    const picgraphic = store.BNMap.graphic(point, symbolStyle)
    // 添加到地图
    clickLayer.add(picgraphic)
    store.BNMap.addGraphicsLayer(clickLayer)
  }
};

// 回显点
const drawPoint = (points) => {
  points = points.split(',')
  const symbolStyle = store.BNSymbol.PictureMarkerSymbol(image.point, 20, 25)
  store.BNMap.removeGraphicsLayer('lableLayer')
  // 向地图添加临时图层
  const lableLayer = store.BNMap.creatGraphicsLayer({ id: 'lableLayer' })
  lableLayer.removeAll()
    // 创建点
    const point = store.BNMap.createPoint({
      x: points[0],
      y: points[1],
      spatialReference: store.BNMap.spatialReference
    })
    //创建graphic
    const markerGraphic = store.BNMap.graphic(point, symbolStyle)
    lableLayer.add(markerGraphic)
    store.BNMap.bindEvent("lableLayer", "click", function(evt){
      store.BASE.move(lableLayer)
    })
    store.BNMap.addGraphicsLayer(lableLayer)
}
/**
 * 编辑功能
 * @param row
 */

const hiddenMe = (_row: any, column: undefined) => {
  // eslint-disable-next-line eqeqeq
  if (column !== undefined) {
    isEdit.value = false
    isSelect.value = false
  }
}

const Submit = async () => {
  // 通过FilterRef这个引用获取对应组件下面所有控件的值,FilterRef.value.getParams()
  const flag = await FilterRef.value?.validateRuleFormRef()
  if (flag) {
    const filter = FilterRef.value.getParams()  
    if (filter.useOrgans.length !== 0) {
      const originalValue = filter.useOrgans
      const parsedValue = originalValue[0].split(',')
      const organId = parsedValue[0]
      const organName = parsedValue[1]
      const modifiedValue = [{
        organId,
        organName
      }]
      filter.useOrgans = modifiedValue
    } 
    if (/^\d+/.test(filter.owners)) {
      const ownersStr = filter.owners
      const matches = ownersStr.match(/(\d+)([^\d]+)/)
      const organId = matches[1]
      const organName = matches[2]
      const ownersObj = {
        organId,
        organName
      }
      filter.owners = ownersObj
    }
    filter.eqptCode = filter.eqptCode.replace(/\s+/g, "")
    if (filter.eqptModel) {
      filter.eqptModel = filter.eqptModel.replace(/\s+/g, "")
    }
    if (filter.position) {
      filter.position = filter.position.replace(/\s+/g, "")
    }
    filter.eqptName = filter.eqptName.replace(/\s+/g, "")
    const newfilter = {
        eqptCode: filter.eqptCode, //设备编号
        owners: filter.owners, //归属单位
        eqptName: filter.eqptName, //设备名称
        typeId: typeId.value //设备类型
      }
      if (filter.eqptModel !== undefined) {
        newfilter.eqptModel = filter.eqptModel //设备型号      
      }
      if (filter.useOrgans.length !== 0) {
        newfilter.useOrgans = filter.useOrgans //使用部门
      }
      if (filter.position !== undefined) {
        newfilter.position = filter.position // 位置
      }
      if (filter.region !== undefined) {
        newfilter.region = filter.region //区域
      }
      if (filter.coordinate !== undefined) {
        newfilter.coordinate = filter.coordinate
      }
    if (addTilte.value === '编辑设施设备') {
      if (filter.coordinate.length !== 0) {  
        let location = filter.coordinate.split(',');
        filter.coordinate = {latitude: location[0].substr(1).trim(), longitude:location[1].substr(0, location[1].length-1).trim()};
      }
      newfilter.eqptId = eqptId.value
      newfilter.coordinate = filter.coordinate
      waterUpdate(newfilter).then(res => {
        getData()
        addEquipmentDialogVisible.value = false
        ElMessage.success('修改成功！')
      }).catch(res => {
        ElMessage.error(res?.message || '修改失败')
      })
    } else {
      if (filter.coordinate !== undefined) {
        const coordinateString = filter.coordinate
        const xValue = coordinateString.split(',')[0].trim()
        const yValue = coordinateString.split(',')[1].trim()
        mapPoint.value.x = parseFloat(xValue)
        mapPoint.value.y = parseFloat(yValue)
      }
      if (!mapPoint.value.x && !mapPoint.value.y) {
        filter.coordinate = undefined
      } else {
        filter.coordinate = { latitude: mapPoint.value.x, longitude: mapPoint.value.y }
      }
      newfilter.coordinate = filter.coordinate
      waterAdd(newfilter)
        .then((res) => {
          getData()
          addEquipmentDialogVisible.value = false
          ElMessage.success('增加成功！')
        })
        .catch((res: any) => {
          ElMessage.error(res?.message || '增加失败')
        })
    }
  }
}

const Cancel = () => {
  isdialogEditOptions.value[5].inputProps.data = []
  isdialogEditOptions.value[1].inputProps.data = []

  dialogEditOptions.forEach(e => {
    e.defaultValue = []
  })

  mapPoint.value.x = ""
  mapPoint.value.y = ""
  thresholdDialogVisible.value = false
  showMapDialogVisible.value = false
  addEquipmentDialogVisible.value = false
}

//点击地图坐标图标返回地图页面
dialogEditOptions.forEach(e => {
  if (e.prop == "coordinate") {
    e.events.click = function(value, evt) {
      back();
    };
  }
});

const back = () => { 
  addEquipmentDialogVisible.value = false
  showMapDialogVisible.value = true
  const filter = FilterRef.value.getParams()
  setTimeout(() => {
    drawPoint(filter.coordinate)
  },3000)
}

const jump = () => {
  showMapDialogVisible.value = false
  addEquipmentDialogVisible.value = true
}

const next = (data: FilterDataType) => {
  showMapDialogVisible.value = false
  addEquipmentDialogVisible.value = true
  // 以下数据都是直接写的，需要改为从接口中获取数据
  dialogEditOptions.forEach(e => {
    if (e.prop === 'coordinate') {
      e.inputProps.placeholder = '请输入地图坐标'
      e.events.click = function (value, evt) {
        back(value)
      }
    }
  })
  nextTick(() => {
    if (mapPoint.value.x !== undefined && mapPoint.value.y !== undefined) {
      FilterRef.value.setFieldsValue({
        coordinate: mapPoint.value.x + ',' + mapPoint.value.y
      })
    }
  })
}
// 表单验证规则
const rules = reactive({
  eqptCode: [{required: true,message: '请输入设备编号',trigger: 'blur',
  validator: (rule: any, value: any) => {
      const trimmedValue = value.trim()
      if (trimmedValue === '') {
        // eslint-disable-next-line prefer-promise-reject-errors
        return Promise.reject('请输入设备编号')
      } else {
        return Promise.resolve()
      }
    }}],
  eqptType: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
  eqptName: [{required: true,message: '请输入设备名称',trigger: 'change',
  validator: (rule: any, value: any) => {
      const trimmedValue = value.trim()
      if (trimmedValue === '') {
        // eslint-disable-next-line prefer-promise-reject-errors
        return Promise.reject('请输入设备名称')
      } else {
        return Promise.resolve()
      }
    } }],
  owners: [{ required: true, message: '请选择归属单位', trigger: 'change'  }]
})

const loading = ref(false)
const tableData = ref<ProblemType[]>([])
const pager = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageCount: 1
})

const search = ref<SearchType>({})

/**
 * 向api传参，进行条件查询
 */
/**
  * 功能-获取数据、分页查询
  * Date: 2023-8-2
  * Author: 郑钦懋、王泽同
  */
const getData = async () => {
  loading.value = true
  const payload: PageListType = {
    pageNum: pager.currentPage,
    pageSize: pager.pageSize,
    condition: {
    }
  }
  // 传递查询的内容到api
  if (search.value.eqptCode) {
    var str = search.value.eqptCode
    payload.eqptCode = str.replace(/\s+/g, "")
  }
  if (search.value.terminal && search.value.terminal.length > 0) {
    payload.type = search.value.terminal.join(',') || ''
    payload.terminal = payload.type.split(',')
  }
  if (search.value.region && search.value.region.length > 0) {
    const region = []
    isdeviceOptions.value[0].inputProps.options.forEach(item => {
      search.value.region.forEach(i => {
        if (item.value === i) {
          region.push(item.label)
        }
      })
    })
    payload.region1 = region || ''
  }
  if (search.value.order) {
    payload.order = search.value.order || ''
  }
  /**
   * 获取数据
   */
  // res获取查询后的数据列表
  // res2未加查询条件的数据列
  // 获取数据列表，无法获取转圈圈
  await waterPageList(payload).then(res=>{
    tableData.value = res.data.list  
    pager.total = res.data.total
    if(pager.total === 0){
      pager.pageCount = 1
    }else{
      pager.pageCount = Math.ceil(pager.total / pager.pageSize)
    }
    loading.value = false
  }).catch(err => {
    loading.value = false
    ElMessage.error(err?.message || "获取失败");
  })

  
}

// 记得让columns.ts里面的对应thresholdListColumns的字段名和后端数据保持一致
const thresholdData = ref([
  // { id: '1', area: '区域A', historicalAverage: '13', isAlarm: '否', setThreshold: '/' },
  // { id: '2', area: '区域B', historicalAverage: '30', isAlarm: '是', setThreshold: '13' },
  // { id: '3', area: '区域C', historicalAverage: '23', isAlarm: '否', setThreshold: '22' },
  // { id: '4', area: '区域D', historicalAverage: '15', isAlarm: '是', setThreshold: '' },
  // { id: '5', area: '区域E', historicalAverage: '27', isAlarm: '否', setThreshold: '' },
  // { id: '6', area: '区域F', historicalAverage: '18', isAlarm: '是', setThreshold: '' }
])

// <!--
// * 功能-按钮执行
// * Date: 2023-7-29
// * Author: 靳从毅
// * val:传过来的参数执行相应的代码
//  -->
const handleCreate = (val: string) => {
  timer.value = new Date().getTime()
  if (val === 'threshold') {
    // 弹窗标题
    // * 功能-数据阈值实现,暂无第三方接口,死数据渲染
    // * Date: 2023-7-29
    // * Author: 靳从毅
    addTilte.value = '设置维护提醒'
    showMapDialogVisible.value = false
    thresholdDialogVisible.value = true
  } else if (val === 'export') {
    // * 功能-导出数据
    // * Date: 2023-8-2
    // * Author: 刘润
    showMapDialogVisible.value = false
    thresholdDialogVisible.value = false
    const payload: PageListType = {
    }
    if (search.value.eqptCode) {
      payload.eqptCode = search.value.eqptCode || ''
    }
    if (search.value.terminal && search.value.terminal.length > 0) {
      payload.type = search.value.terminal.join(',') || ''
      payload.terminal = payload.type.split(',')
    }
    if (search.value.region && search.value.region.length > 0) {
      const region = []
      isdeviceOptions.value[0].inputProps.options.forEach(item => {
        search.value.region.forEach(i => {
          if (item.value === i) {
            region.push(item.label)
          }
        })
      })
      payload.region1 = region || ''
    }
    if (search.value.order) {
      payload.order = search.value.order || ''
    }

    listExport(payload)
      .then((res) => {
        const link = document.createElement('a')
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        const nowTime = dayjs().format('YYYYMMDD')
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        link.setAttribute('download', `饮水机管理信息列表${nowTime}.xlsx`) // 报表名称可自定义
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      })
      .catch((res: any) => {
        ElMessage.error(res?.message || '导出失败')
      })
  } else if (val === 'download') {
    // * 功能-模板下载
    // * Date: 2023-8-2
    // * Author: 刘润
    showMapDialogVisible.value = false
    thresholdDialogVisible.value = false
    listDownload().then((res: any) => {
      const link = document.createElement('a')
      const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
      link.style.display = 'none'
      link.href = URL.createObjectURL(blob)
      link.setAttribute('download', '饮水机导入模板.xlsx') // 报表名称可自定义
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }).catch((res: any) => {
      ElMessage.error(res?.message || '导出失败')
    })
  } else if (val === 'add') {
    // 弹窗标题
    // * 功能-新增数据
    // * Date: 2023-8-1
    // * Author: 王泽同
    addTilte.value = '新增设施设备'
    dialogEditOptions.forEach(e => {
      e.defaultValue = ''
    })
    mapPoint.value.x = ""
    mapPoint.value.y = ""
    showMapDialogVisible.value = true
    thresholdDialogVisible.value = false
  }
}

// 单击 出现输入框
// setThreshold 和 isAlarm 的字段名和后端数据保持一致
const cellClick = (val: any) => {
  if (val.column.property === 'setThreshold') {
    isEdit.value = true
    isSelect.value = false
    rowInd.value = val.$index
    colInd.value = val.cellIndex
  } else if (val.column.property === 'isAlarm') {
    isSelect.value = true
    isEdit.value = false
    rowInd.value = val.$index
    colInd.value = val.cellIndex
  }
}

/**
 * 数据导入
 */
// * 功能-导入数据
// * Date: 2023-8-3
// * Author: 刘润，王泽同
// 请求用户的权限树
const { getters } = useStore()
// 拿到vuex里面用户的信息
const stores = useStore()
const organTree = stores.state.user.organTree// 获取树
const UserInfo = computed(() => getters['user/getOrganTree'])
const Users = computed(() => getters['user/getUserInfo'])
const upload = ref<UploadInstance>()

const btnLoading = ref(false) // 导入按钮加载状态

const handleImport = (uploadFile: UploadFile) => {
  if (!btnLoading.value) {
    btnLoading.value = true
    const formData = new FormData()
    formData.append('multipartFile', uploadFile.raw)
    listImport(formData).then((res: any) => {
      if (res === 'success') {
        ElMessage.success('导入成功')
        pager.currentPage = 1
        pager.pageSize = 10
        getData()
        
      } else {
        ElMessage.error(res?.message || '导入失败')
      }
      btnLoading.value = false
    }).catch((res) => {
      ElMessage.error('导入失败')
      btnLoading.value = false
    })
    setTimeout(() => {
          upload.value!.clearFiles()
        }, 1000)
  }
}

// 获取数据字典
/**
  * 功能-获取数据字典数据、渲染页面
  * Date: 2023-8-1
  * Author: 王泽同
  */
const getTerminal = async () => {
  const res = getResource('terminal').then(
    (res) => {
      isdeviceOptions.value.forEach((e) => {
        if (e.prop === 'terminal') {
          e.inputProps.options = res.data.properties.meta
        }
      })
    }
  )
}

const getRegion = () => {
  getResource('resource_area').then(
    (res) => {
      let regions = res.data.properties.meta;
      for(let i = 0; i < regions.length; i++){
        var region  = {
          id: i,
          area: regions[i].label,
          historicalAverage: "30",
          isAlarm: regions[i].alert?"是":"否",
          setThreshold: "13"
        };
        thresholdData.value.push(region);
      }

      res.data.properties.meta.unshift({ label: '全部', value: '' })
      isdeviceOptions.value[0].inputProps.options = res.data.properties.meta
      isdeviceOptions.value[0].inputProps.options[1].alert = true
    }
  )
}

// 分页
const sizeChange = (size: number) => {
  pager.pageSize = size
  getData()
}
const currentChange = (value: number) => {
  pager.currentPage = value
  getData()
}

/**
 * 编辑功能
 * @param row
 */
// * 功能-编辑功能
// * Date: 2023-8-3
// * Author: 郑钦懋
// * row: 当前列的数据
const typeId = ref()
const handleEdit = (row) => {
  // 该循环用于进行编辑页面数据回显，需要字段对应
  dialogEditOptions.forEach(e => {
    eqptId.value = row.eqptId
    if (e.prop === 'useOrgans') {
      e.inputProps.options.forEach(item => {
        if (row.useOrgans === item.label) {
          e.defaultValue = [item.value]
        }
      })
    } else if (e.prop === 'owners') {
      e.inputProps.options.forEach(item => {
        if (row.owners === item.label) {
          e.defaultValue = item.value
          const ownersStr = item.value
          const matches = ownersStr.match(/(\d+)([^\d]+)/)
          const id = matches[1]
          setEqptType(id)
        }
      })
    } else if (e.prop === 'coordinate') {
      if (row[e.prop] === undefined) {
        e.defaultValue = []
      } else {
        e.defaultValue = '(' + row[e.prop].latitude + ',' + row[e.prop].longitude + ')'
        mapPoint.value.x = row[e.prop].latitude
        mapPoint.value.y = row[e.prop].longitude
      }
    } else if (e.prop === 'eqptType') {
      e.defaultValue = row.typeName
      typeId.value = row.typeId
      
    }  else if (row[e.prop] !== null) {
      e.defaultValue = row[e.prop]
    }
  })
  timer.value = new Date().getTime()
  addTilte.value = '编辑设施设备'
  addEquipmentDialogVisible.value = true
}

/**
 * 删除
 * @param row
 */
// * 功能-删除功能
// * Date: 2023-8-3
// * Author: 郑钦懋
// * row: 当前列的数据
const handleDelete = async (row: ProblemType) => {
  await waterDelete(row.eqptId).then(() =>{
    getData()
    ElMessage.success('已删除！')
  }).catch(res =>{
    ElMessage.error(res.message || '删除失败，请重试！')
  })
}

const isdialogEditOptions = ref(dialogEditOptions)
const getOwners = () => {
  isdialogEditOptions.value.forEach((e) => {
    if (e.prop === 'useOrgans') {
      const organ = []
      if(organTree.length > 0){
        organTree[0].children.forEach(organ1 => {
          organ.push({ label: organ1.data.name, value: organ1.data.organId + ',' + organ1.data.name })
        })
      }     
      isdialogEditOptions.value[4].inputProps.options = organ
    }
    if (e.prop === 'owners') {
      const owner = []
      if(UserInfo.value.length > 0){
        UserInfo.value[0].children[0].children.forEach(item => {
          owner.push({ label: item.data.name, value: item.data.organId + item.data.name })
        })
      }      
      isdialogEditOptions.value[1].inputProps.options = owner
      e.events.change = async (value, evt) => {
        const matches = value.match(/(\d+)([^\d]+)/)
        const id = matches[1]
        FilterRef.value.setFieldsValue({
          eqptType: null
        })
        setEqptType(id)
      }
    }
    if (e.prop === 'eqptType') {
      e.events.change = async (value, evt) => {
        typeId.value = value
      }
    }
  })
}

/**
 * 回显设备类型
 * Date: 2023-09-08
 * Author: 靳从毅
 * @param id 归属单位id
 */
const setEqptType = async (id) => {
  const res = await geteqptType({ owners: [id] })
  const array1 = []
  isdialogEditOptions.value.forEach((e) => {
    if (e.prop === 'eqptType') {
      res.data.forEach(item => {
        const keyword = '饮水机'
        const regex = new RegExp(keyword, 'i') // i表示不区分大小写
        // if (regex.test(item.typeName)) {
          array1.push(extractTreeData(item))
        // }
      })
    }
  })
  isdialogEditOptions.value[5].inputProps.data = array1
}

/**
 * 将设备类型变为树
 * Date: 2023-09-08
 * Author: 靳从毅
 * @param item 设备类型数据
 */
const extractTreeData = (item) => {
  return {
    label: item.typeName,
    value: item.typeId,
    children: item.children.map(child => extractTreeData(child))
  }
}
/**
 * 排序
 * Date: 2023-8-1
 * Author: 郑钦懋
 * @param column 排序顺序
 */

const handleSort = (column: any) => {
  const prop = column.prop
  let order = column.order
  if (order === 'descending') {
    order = 'desc'
  } else if (order === 'ascending') {
    order = 'asc'
  }
  search.value.order = [{ column: prop, method: order }]
  getData()
}
// 默认按照设备编号最小的排序
handleSort({ order: 'ascending', prop: 'eqptCode' })

onBeforeMount(() => {
  getTerminal()
  getRegion()
  getOwners()
})
</script>

<style scoped>
.list-action {
  display: flex;
}
</style>
